<!-- 笔试记录页面 -->
<template>
  <div class="written-record-container">
    <div class="header">
      <h2>笔试记录</h2>
      <div class="actions">
        <a-button type="primary" @click="startNewExam">
          <template #icon>
            <plus-outlined />
          </template>
          开始新笔试
        </a-button>
      </div>
    </div>

    <a-card class="record-card">
      <!-- 筛选区域 -->
      <div class="filter-section">
        <a-row :gutter="24">
          <a-col :span="6">
            <a-select
              v-model:value="filters.position"
              placeholder="岗位筛选"
              style="width: 100%"
              allowClear
            >
              <a-select-option v-for="pos in positions" :key="pos" :value="pos">
                {{ pos }}
              </a-select-option>
            </a-select>
          </a-col>
          <a-col :span="6">
            <a-select
              v-model:value="filters.status"
              placeholder="状态筛选"
              style="width: 100%"
              allowClear
            >
              <a-select-option v-for="(color, status) in statusMap" :key="status" :value="status">
                <a-tag :color="color">{{ status }}</a-tag>
              </a-select-option>
            </a-select>
          </a-col>
          <a-col :span="8">
            <a-range-picker
              v-model:value="filters.dateRange"
              style="width: 100%"
              :placeholder="['时间范围开始', '时间范围结束']"
            />
          </a-col>
          <a-col :span="4" style="text-align: right">
            <a-button type="primary" @click="applyFilters">筛选</a-button>
            <a-button style="margin-left: 8px" @click="resetFilters">重置</a-button>
          </a-col>
        </a-row>
      </div>

      <!-- 表格区域 -->
      <a-table
        :columns="columns"
        :data-source="filteredRecords"
        :pagination="pagination"
        :loading="loading"
        row-key="id"
        :scroll="{ x: 'max-content' }"
        bordered
        class="record-table"
      >
        <!-- 笔试岗位列 -->
        <template #position="{ text, record }">
          <span class="position-title">{{ text }}</span>
          <div class="company-name">{{ record.company }}</div>
        </template>

        <!-- 耗时列 -->
        <template #duration="{ record }">
          <span>{{ formatDuration(record.duration) }}</span>
        </template>

        <!-- 状态列 -->
        <template #status="{ text }">
          <a-tag :color="getStatusColor(text)">
            {{ text }}
          </a-tag>
        </template>

        <!-- 操作列 -->
        <template #action="{ record }">
          <a-button type="link" @click="viewReport(record)" :disabled="!canViewReport(record)">
            查看报告
          </a-button>
          <a-button type="link" @click="continueExam(record)" v-if="record.status === '进行中'">
            继续
          </a-button>
          <a-popconfirm
            title="确定要删除此笔试记录吗？"
            ok-text="确定"
            cancel-text="取消"
            @confirm="deleteRecord(record)"
          >
            <a-button type="link" danger>删除</a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import {
  Card as ACard,
  Table as ATable,
  Button as AButton,
  Tag as ATag,
  Select as ASelect,
  SelectOption as ASelectOption,
  Row as ARow,
  Col as ACol,
  RangePicker as ARangePicker,
  Popconfirm as APopconfirm,
  message,
} from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import { deleteExamUsingGet, getExamListUsingGet } from '@/api/examController'
import { formatDuration } from '@/utils/FormatTime'

const router = useRouter()
const loading = ref(false)

// 表格列定义
const columns = [
  {
    title: '笔试岗位',
    dataIndex: 'position',
    key: 'position',
    width: 200,
    slots: { customRender: 'position' },
    sorter: (a, b) => a.position.localeCompare(b.position),
  },
  {
    title: '笔试时间',
    dataIndex: 'examTime',
    key: 'examTime',
    width: 180,
    sorter: (a, b) => new Date(a.examTime) - new Date(b.examTime),
  },
  {
    title: '耗时',
    dataIndex: 'duration',
    key: 'duration',
    width: 120,
    sorter: (a, b) => a.duration - b.duration,
    slots: { customRender: 'duration' },
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 120,
    slots: { customRender: 'status' },
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
    width: 180,
    align: 'center',
    slots: { customRender: 'action' },
  },
]

// 状态颜色映射
const statusMap = {
  已完成: 'green',
  分析中: 'blue',
  未完成: 'red',
}
const statusTextMap = {
  0: '未完成',
  1: '分析中',
  2: '已完成',
}

// 筛选条件
const filters = ref({
  position: undefined,
  status: undefined,
  dateRange: [],
})

// 岗位列表（从记录中提取）
const positions = computed(() => {
  const posSet = new Set()
  writtenRecords.value.forEach((record) => posSet.add(record.position))
  return Array.from(posSet)
})

// 分页配置
const pagination = ref({
  pageSize: 5,
  showSizeChanger: false,
  pageSizeOptions: ['5', '10', '20', '50'],
  showTotal: (total) => `共 ${total} 条记录`,
  position: ['bottomRight'],
})

const writtenRecords = ref([]) // 初始化为空

const fetchWrittenData = async () => {
  loading.value = true
  try {
    const res = await getExamListUsingGet()
    if (res && res.code === 0 && Array.isArray(res.data)) {
      writtenRecords.value = res.data.map((item) => ({
        id: item.id,
        position: item.position,
        company: item.company,
        examTime: item.createTime ? formatDate(item.createTime) : '',
        duration: item.examDuration,
        questionCount: item.questionCount || 0, // 若无则为0
        status: statusTextMap[item.examStatus],
      }))
    }
  } catch (e) {
    message.error('获取笔试数据失败')
  } finally {
    loading.value = false
  }
}

function formatDate(dateStr) {
  const d = new Date(dateStr)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(
    d.getDate(),
  ).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(
    2,
    '0',
  )}`
}

// 筛选后的记录
const filteredRecords = computed(() => {
  return writtenRecords.value.filter((record) => {
    // 岗位筛选
    if (filters.value.position && record.position !== filters.value.position) {
      return false
    }

    // 状态筛选
    if (filters.value.status && record.status !== filters.value.status) {
      return false
    }

    // 日期范围筛选
    if (filters.value.dateRange && filters.value.dateRange.length === 2) {
      const recordDate = new Date(record.examTime)
      const startDate = filters.value.dateRange[0]
      const endDate = filters.value.dateRange[1]

      if (recordDate < startDate || recordDate > endDate) {
        return false
      }
    }

    return true
  })
})

// 获取状态标签颜色
const getStatusColor = (status) => {
  return statusMap[status] || 'default'
}

// 是否可以查看报告
const canViewReport = (record) => {
  return ['已完成'].includes(record.status)
}

// 应用筛选条件
const applyFilters = () => {
  message.success('筛选条件已应用')
}

// 重置筛选条件
const resetFilters = () => {
  filters.value = {
    position: undefined,
    status: undefined,
    dateRange: [],
  }
  message.info('筛选条件已重置')
}

// 开始新笔试
const startNewExam = () => {
  message.info('准备开始新的笔试')
  router.push('/written/tec')
}

// 查看笔试报告
const viewReport = (record) => {
  message.success(`查看 ${record.position} 的笔试报告`)
  router.push(`/api/written/analyze?examId=${record.id}`)
}

// 继续笔试
const continueExam = (record) => {
  message.info(`继续进行 ${record.position} 的笔试`)
  router.push(`/written/exam/${record.id}`)
}

// 删除笔试记录
const deleteRecord = async (record) => {
  const res = await deleteExamUsingGet({
    examId: record.id,
  })
  if (res && res.code === 0) {
    message.success('删除成功')
    //重新获取笔试记录
    await fetchWrittenData()
  } else {
    message.error('删除失败')
  }
}

onMounted(async () => {
  //发送请求获取用户考试记录信息
  await fetchWrittenData()
})
</script>

<style scoped>
.written-record-container {
  padding: 24px;
  height: 100%;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header h2 {
  font-size: 24px;
  color: #2c3e50;
  margin: 0;
}

.record-card {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  height: auto;
  min-height: calc(100vh - 180px);
  max-height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.filter-section {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

/* 岗位和公司显示样式 */
.position-title {
  font-weight: 500;
  color: #1890ff;
  display: block;
}

.company-name {
  font-size: 12px;
  color: #8c8c8c;
  margin-top: 4px;
}

/* 表格样式 */
.record-table {
  flex: 1;
}

:deep(.ant-table) {
  margin-bottom: 0;
}

:deep(.ant-table-container) {
  overflow: visible;
}

:deep(.ant-table-body) {
  overflow-y: auto !important;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #f5f7fa;
  color: #333;
  font-weight: 500;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #f0f7ff;
}

:deep(.ant-table-pagination) {
  margin: 16px 0;
  position: relative !important;
  display: flex;
  justify-content: flex-end;
  width: 100%;
}

/* 确保分页控件不会被截断 */
:deep(.ant-pagination) {
  margin-bottom: 16px !important;
}

:deep(.ant-pagination-options) {
  display: none;
}

:deep(.ant-table-pagination-right) {
  justify-content: flex-end !important;
  padding-right: 16px;
}

:deep(.ant-btn-primary) {
  background: #1890ff;
  border-color: #1890ff;
}

:deep(.ant-btn-primary:hover) {
  background: #40a9ff;
  border-color: #40a9ff;
}

:deep(.ant-btn-link) {
  padding: 0 8px;
}

:deep(.ant-btn-link[disabled]) {
  color: rgba(0, 0, 0, 0.25);
}

/* 修复表格内部滚动问题 */
:deep(.ant-card-body) {
  padding: 20px;
  display: flex;
  flex-direction: column;
  height: 100%;
}

:deep(.ant-table-wrapper) {
  flex: 1;
  display: flex;
  flex-direction: column;
}

:deep(.ant-spin-nested-loading) {
  flex: 1;
  display: flex;
  flex-direction: column;
}

:deep(.ant-spin-container) {
  flex: 1;
  display: flex;
  flex-direction: column;
}
</style>
